/**
 * This file is part of Megasquirt Logger for PalmOS.
 * Copyright (C) 2011 Andrew Beard
 *
 * Megasquirt Logger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Megasquirt Logger is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Megasquirt Logger.  If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once
#include <DateTime.h>
#include <VfsMgr.h>

class LogFile
{
  public:
    LogFile( DateTimeType tDateTime );
    ~LogFile();
    
    bool IsFileOpen        ( void ) const;
    void TestWrite         ( const Char* pString );
    void WriteHeader       ( DateTimeType tDateTime,
                             const Char*  pFirmwareSignature,
                             UInt16       nRealTimeUpdateLength );
    void WriteOutputRecord ( const UInt8* pData );
    void WriteMarkerRecord ( DateTimeType tTimestamp );
    Err  GetLastError      ( void ) const;
  
  private:
    #pragma options align=packed
    typedef struct
    {
        Char   fileFormat[ 6 ];
        UInt16 formatVersion;
        UInt32 timestamp;
        Char   firmwareSignature[ 63 ];
        UInt32 dataBeginIndex;
        UInt16 outputLength;
    } T_FRD_HeaderType;
    #pragma options align=reset
    
    #pragma options align=packed
    typedef struct
    {
        UInt8 recordType;
        UInt8 counter;
    } T_RecordHeaderType;
    #pragma options align=reset
    
    typedef enum
    {
        OUTPUT_RECORD = 1,
        MARKER_RECORD = 2
    } E_RecordTypes;
  
  private:
    void   CreateFilename  ( DateTimeType tDateTime,
                             Char*        pFilenameBuffer ) const;
    UInt16 FindFirstVolume ( void ) const;
    UInt32 GetUnixTime     ( const DateTimeType* pDateTime ) const;
                         
  private:
    static const UInt16 MAX_FILENAME_LENGTH      = 32;
    static const UInt16 FRD_FORMAT_VERSION       = 1;
    static const UInt32 PALM_TO_UNIX_TIME_OFFSET = 2082844800L;
    static const UInt16 LOG_HEADER_LENGTH        = 81;
  
    static const Char*  LOG_FILENAME_EXTENSION;  
  
    Char*   m_pFilename;
    UInt8   m_nRecordCount;
    FileRef m_LogFile;
    Err     m_LastError;
    UInt16  m_nRealTimeUpdateLength;
};